//
//  MeVC.m
//  ZZLC
//
//  Created by 杨春至 on 2017/12/13.
//  Copyright © 2017年 ZhongZeng. All rights reserved.
//

#import "MeVC.h"
#import "MeHomeHeaderCollectionReusableView.h"
#import "MeCollectionViewCell.h"
#import "PersonCenterVC.h"
#import "ZZLCHelperCenterVC.h"
#import "ChongzhiVC.h"
#import "TiXianiVC.h"
#import "ZZLCTradeHistoryVC.h"
#import "AssetDetailVC.h"
#import "MyInvestmentVC.h"
#import "InvestmentBaseVC.h"
#import "ZZLCLoginVC.h"
#import "ZZLCRegisterVC.h"
#import "Me_UNLOGINView.h"
#import "Me_Model.h"
#import "ZZBaseNavigationController.h"
#import "AuthenticationVC.h"
#import "ZZLCMoreSettingVC.h"
#import "RingAssetDetailVC.h"


@interface MeVC ()<UICollectionViewDelegate,UICollectionViewDataSource>
@property(nonatomic)UICollectionView *collectionView;
@property(nonatomic)NSArray *iconDataSource;
@property(nonatomic)NSArray *contentDataSource;
@property(nonatomic)UIImageView *maskView;
@property(nonatomic)Me_UNLOGINView *unloginView;
@property (copy, nonatomic)  NSString *totolMoneyLabelStr;
@property (copy, nonatomic)  NSString *yesterdayInterestLabelStr;
@property (copy, nonatomic)  NSString *allInterestLabelStr;
@property (copy, nonatomic)  NSString *availableMoneyLabelStr;
//是否已经实名认证
@property (nonatomic,assign) BOOL isVerified;
//是否有交易密码
@property (nonatomic,assign) BOOL isPayPwd;

@property (nonatomic,strong) UIWindow *nowWindow;
@end

@implementation MeVC
- (void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];

//根据当前状态决定是否显影 登录控件
    _maskView.alpha = ![UserModel isLogin];
    if (![UserModel isLogin]) {
//根据状态更新ui
        Me_Model *model = [[Me_Model alloc]init];
        [self configUIByModel:model];
    }else{
        [self loadData];
    }
    [self.navigationController.navigationBar setShadowImage:[UIImage new]];
    
}
- (void)viewWillDisappear:(BOOL)animated{
    [super viewWillDisappear:animated];
    _maskView.alpha = 0;
    [self.navigationController.navigationBar setShadowImage:nil];
}
- (void)viewDidLoad {
    K_WS(weakSelf);
    [super viewDidLoad];
    [self configureNav];
    
    [self.view addSubview:self.collectionView];
    UIImageView *maskView = [[UIImageView alloc]init];
    self.nowWindow = [UIApplication sharedApplication].keyWindow;
    [self.nowWindow addSubview:maskView];
    self.maskView = maskView;
    maskView.image = Image(@"me_mask");
    _maskView.userInteractionEnabled = YES;
    [maskView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(@0);
        make.top.equalTo(@0);
        if (KHeight == 812) {
              make.bottom.equalTo(@(-49.3-34));
        }else{
             make.bottom.equalTo(@(-49.3));
        }
        make.width.equalTo(self.nowWindow);
    }];
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(isLogionAction) name:K_NOTIFICATION_ISLOGIN_SUCCESS object:nil];
    [weakSelf setingMe_UNLOGINView];
    _maskView.alpha = [UserModel isLogin];
    self.collectionView.userInteractionEnabled = [UserModel isLogin];

}
- (void)dealloc
{
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}
#pragma mark privateAction
- (void)loginAction
{
    
    ZZLCLoginVC *loginVC = [[ZZLCLoginVC alloc]initWithNibName:@"ZZLCLoginVC" bundle:nil];
    ZZBaseNavigationController *nav = [[ZZBaseNavigationController alloc]initWithRootViewController:loginVC];
    [self.navigationController presentViewController:nav animated:YES completion:nil];
}
- (void)registerAction
{
    ZZLCRegisterVC *registerVC = [[ZZLCRegisterVC alloc]initWithNibName:@"ZZLCRegisterVC" bundle:nil];
    registerVC.getValidationCode = GetValidationCodeFormRegister;
    ZZBaseNavigationController *nav = [[ZZBaseNavigationController alloc]initWithRootViewController:registerVC];
    [self.navigationController presentViewController:nav animated:YES completion:nil];
}
#pragma mark 登录成功通知
- (void)isLogionAction
{
    if ([UserModel isLogin]) {
        //todo 如果未登录,那么创建这些未登录的视图
        self.collectionView.userInteractionEnabled = YES;
        _maskView.alpha = 0;
        self.collectionView.userInteractionEnabled = YES;
    }
    else
    {
        _maskView.alpha = 1;
        [self setingMe_UNLOGINView];
        self.collectionView.userInteractionEnabled = false;
    }
    [self configureNav];
    
}
- (void)loadData
{

    self.contentDataSource = @[@"我的投资",@"交易记录",@"帮助中心",@"客服电话",@"更多设置"];
    self.iconDataSource = @[@"me_my",@"me_tradeHistory",@"me_helpCenter",@"me_phone",@"me_moreSeting"];
    [NetWorkingManager postWithRequestUrl:@"User/showMyAccount" AndParameters:@{@"parameters":[@{@"authorization":[UserModel authorization]?[UserModel authorization]:@""} DataTOjsonStringAndAddVersion]} AndRequestBlock:^(NSDictionary *responseObject) {
        NSLog(@"UserModel userName%@",[UserModel userName]);
        [self configUIByData:responseObject];
    } FailBlock:^(NSDictionary *errDic) {
        NSLog(@"%@",errDic);
    }];
}
- (void)configUIByData:(NSDictionary*)dic
{
    NSDictionary *userDic = dic[@"obj"];
    Me_Model *meModel = [Me_Model objectWithKeyValues:userDic];
    [self configUIByModel:meModel];
    if ([[dic allKeys] containsObject:@"list"]) {
        NSArray *listArray =dic[@"list"];
        NSDictionary *bankDic = listArray[0];
        [[NSUserDefaults standardUserDefaults]setObject:[NSJSONSerialization dataWithJSONObject:bankDic options:NSJSONWritingPrettyPrinted error:nil]forKey:K_BANK_MODEL];
    }
    
}
- (void)configUIByModel:(Me_Model*)meModel{
    self.totolMoneyLabelStr = [NSString stringWithFormat:@"%0.2f",[meModel.totalMoney doubleValue]/100];
    self.allInterestLabelStr = [NSString stringWithFormat:@"%0.2f",[meModel.allProfit doubleValue]/100];
    self.yesterdayInterestLabelStr = [NSString stringWithFormat:@"%0.2f",[meModel.wfsy doubleValue]/100];
    self.availableMoneyLabelStr = [NSString stringWithFormat:@"%0.2f",[meModel.leftMoney doubleValue]/100];
    self.isVerified = meModel.isBindBank;
    self.isPayPwd = meModel.isPayPwd;
    [self.collectionView reloadData];
}
- (void)configureNav
{
    UIBarButtonItem *leftItem = [[UIBarButtonItem alloc]initWithImage:UIImageMake(@"person") style:UIBarButtonItemStyleDone target:self action:@selector(leftVCShow)];
   
    if ([[NSUserDefaults standardUserDefaults]objectForKey:K_ISLOGIN_SUCCESS]) {
        UIBarButtonItem *leftItems2 = [[UIBarButtonItem alloc]initWithTitle:[UserModel userName] style:UIBarButtonItemStyleDone target:self action:@selector(leftVCShow)];
        self.navigationItem.leftBarButtonItems = @[leftItem,leftItems2];
    }
    else{
        UIBarButtonItem *leftItems2 = [[UIBarButtonItem alloc]initWithTitle:@"未登录" style:UIBarButtonItemStyleDone target:self action:@selector(leftVCShow)];
        self.navigationItem.leftBarButtonItems = @[leftItem,leftItems2];
    }

    UIBarButtonItem *rightItem = [[UIBarButtonItem alloc]initWithImage:UIImageMake(@"me_message") style:UIBarButtonItemStyleDone target:self action:@selector(rightVCShow)];
    self.navigationItem.rightBarButtonItem = rightItem;
}

#pragma mark Action
- (void)leftVCShow
{
    PersonCenterVC *personCenterVC = [[PersonCenterVC alloc]init];
    personCenterVC.isverified = self.isVerified;
    personCenterVC.isPayPwd = self.isPayPwd;
    [self.navigationController pushViewController:personCenterVC animated:YES];
}
- (void)rightVCShow
{
  
}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}
- (UICollectionView *)collectionView{
    if (_collectionView) {
        return _collectionView;
    }
    //确定是水平滚动，还是垂直滚动
    UICollectionViewFlowLayout *flowLayout=[[UICollectionViewFlowLayout alloc] init];
    [flowLayout setScrollDirection:UICollectionViewScrollDirectionVertical];
    _collectionView = [[UICollectionView alloc] initWithFrame:CGRectMake(0,0, K_SCREEN_WIDTH,  K_SCREEN_HEIGHT-K_NAV_HEIGHT) collectionViewLayout:flowLayout];
    _collectionView.backgroundColor = COLORE_GLOBLE_BACKGOUNDCOLOR;
    [_collectionView registerNib:[UINib nibWithNibName:@"MeCollectionViewCell" bundle:[NSBundle mainBundle]] forCellWithReuseIdentifier:@"MeCollectionViewCell"];
    [_collectionView registerNib:[UINib nibWithNibName:@"MeHomeHeaderCollectionReusableView" bundle:nil] forSupplementaryViewOfKind:UICollectionElementKindSectionHeader withReuseIdentifier:@"MeHomeHeaderCollectionReusableView"];
    _collectionView.dataSource = self;
    _collectionView.delegate = self;
    return  _collectionView;
}
#pragma mark -
#pragma mark UICollectionViewDelegateFlowLayout

- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath{

    return (CGSize){K_SCREEN_WIDTH/3.00-1.0f,100};
}

- (CGFloat)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout minimumLineSpacingForSectionAtIndex:(NSInteger)section{
    return 1.0f;
}
- (CGFloat)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout minimumInteritemSpacingForSectionAtIndex:(NSInteger)section{
    return 1.0f;
}

-(CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout referenceSizeForHeaderInSection:(NSInteger)section{

    return (CGSize){K_SCREEN_WIDTH,178+75};
}
- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath
{    K_WS(weakSelf);
    switch (indexPath.row) {
        case 0:
        {
            InvestmentBaseVC *investmentLeftVC = [[InvestmentBaseVC alloc]initWithNibName:@"InvestmentBaseVC" bundle:nil];
            investmentLeftVC.categoryNum = 0;//投资中
               InvestmentBaseVC *investmentRightVC = [[InvestmentBaseVC alloc]initWithNibName:@"InvestmentBaseVC" bundle:nil];
            investmentRightVC.categoryNum = 1;//已还款
            MyInvestmentVC *myInvestmentVC = [[MyInvestmentVC alloc]init];
            myInvestmentVC.VCArray = @[investmentLeftVC, investmentRightVC];
            myInvestmentVC.sectionTitles = @[@"投资中", @"已返款",];
            [weakSelf.navigationController pushViewController:myInvestmentVC animated:YES];
        }
            break;
        case 1:
        {
            ZZLCTradeHistoryVC *tradeHistoryVC = [[ZZLCTradeHistoryVC alloc]initWithNibName:@"ZZLCTradeHistoryVC" bundle:nil];
            [weakSelf.navigationController pushViewController:tradeHistoryVC animated:YES];
        }
            break;
        case 2:
        {
            ZZLCHelperCenterVC *helperCenterVC = [[ZZLCHelperCenterVC alloc]initWithNibName:@"ZZLCHelperCenterVC" bundle:nil];
            [weakSelf.navigationController pushViewController:helperCenterVC animated:YES];
        }
            break;
        case 3:
        {
           [self setupPhone:@"0571-8607-6015"];
        }
            break;
        case 4:
        {
            ZZLCMoreSettingVC *moresettingVC = [[ZZLCMoreSettingVC alloc]initWithNibName:@"ZZLCMoreSettingVC" bundle:nil];
            [weakSelf.navigationController pushViewController:moresettingVC animated:YES];
        }
            break;
        default:
            break;
    }
}
#pragma mark -
#pragma mark UICollectionViewDataSource

- (UICollectionReusableView *)collectionView:(UICollectionView *)collectionView viewForSupplementaryElementOfKind:(NSString *)kind atIndexPath:(NSIndexPath *)indexPath{
    K_WS(weakSelf);
 
        MeHomeHeaderCollectionReusableView *head =  [collectionView dequeueReusableSupplementaryViewOfKind :kind   withReuseIdentifier:@"MeHomeHeaderCollectionReusableView"  forIndexPath:indexPath];
    head.totolMoneyLabel.text = self.totolMoneyLabelStr;//总资金
    head.yesterdayInterestLabel.text = self.yesterdayInterestLabelStr;//待结算收益
    head.allInterestLabel.text = self.allInterestLabelStr;//累计收益
    head.availableMoneyLabel.text = self.availableMoneyLabelStr;//可用余额
    [head.chongzhiBtn bk_whenTapped:^{
        if (_isVerified) {
            ChongzhiVC *chongzhiVC = [[ChongzhiVC alloc]initWithNibName:@"ChongzhiVC" bundle:nil];
            chongzhiVC.titleStr = @"充值";
            chongzhiVC.urlStr = @"User/baofooBindPay";
            [weakSelf.navigationController pushViewController:chongzhiVC animated:YES];
        }else{
            [self jumpTOAuthenVC];
        }
    }];
    [head.tixianBtn bk_whenTapped:^{
        if (_isVerified) {
            TiXianiVC *chongzhiVC = [[TiXianiVC alloc]initWithNibName:@"TiXianiVC" bundle:nil];
            chongzhiVC.titleStr = @"提现";
            chongzhiVC.urlStr = @"User/baofooWithdrawals";
            [weakSelf.navigationController pushViewController:chongzhiVC animated:YES];
        }else{
            [self jumpTOAuthenVC];
        }

    }];
    [head.myAssetLabel bk_whenTapped:^{
        
        RingAssetDetailVC *assetDetailVC = [[RingAssetDetailVC alloc]init];
        [weakSelf.navigationController pushViewController:assetDetailVC animated:YES];
      
    }];
      return head;

    
}

- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section{
    return 5 ;
}



- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath{
 
    MeCollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"MeCollectionViewCell" forIndexPath:indexPath];
    cell.backgroundColor = [UIColor whiteColor];
    cell.iconContentLabel.text = self.contentDataSource[indexPath.row];
    cell.iconImageV.image = [UIImage imageNamed:self.iconDataSource[indexPath.row]];
    return cell;
}
- (void)jumpTOAuthenVC{
    UIAlertController *alterControll = [UIAlertController alertControllerWithTitle:@"温馨提示" message:@"您的账号还未实名认证" preferredStyle:UIAlertControllerStyleAlert];
    UIAlertAction *cancelAction = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:nil];
    UIAlertAction *doneAction = [UIAlertAction actionWithTitle:@"认证" style:UIAlertActionStyleDestructive handler:^(UIAlertAction * _Nonnull action) {
        AuthenticationVC *authenVC = [[AuthenticationVC alloc]init];
        authenVC.hasAuthent = NO;
        [self.navigationController pushViewController:authenVC animated:YES];
    }];
    [alterControll addAction:cancelAction];
    [alterControll addAction:doneAction];
    [self presentViewController:alterControll animated:YES completion:nil];
}
#pragma mark
- (void)setingMe_UNLOGINView
{
    

        Me_UNLOGINView *unloginView = [[Me_UNLOGINView alloc]init];
        [self.maskView addSubview:unloginView];
        self.unloginView = unloginView;
        unloginView.backgroundColor = [UIColor whiteColor];
        [unloginView mas_makeConstraints:^(MASConstraintMaker *make) {
            make.left.equalTo(@0);
            make.right.equalTo(@0);
            make.height.equalTo(@170);
            make.bottom.equalTo(@0);
        }];
    
        [unloginView.loginBtn addTarget:self action:@selector(loginAction) forControlEvents:UIControlEventTouchUpInside];
        [unloginView.registerBtn addTarget:self action:@selector(registerAction) forControlEvents:UIControlEventTouchUpInside];
    
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
